class AddressSelector extends HTMLElement {
    static get observedAttributes() {
        return ['street', 'city', 'state', 'zip', 'country'];
    }
    constructor() {
        super();
        this.templateUrl = '/components/selector/address/index.html';
        this.templateId = 'wcs-selector-address';
        this._countries = [];
        this._states = [];
        this._cities = [];
        // 初始化默认值
        this._street = '';
        this._city = '';
        this._state = '';
        this._zip = '';
        this._country = '';
    }
    async init() {
        const template = await this.getTemplate();
        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'open' });
        // 克隆模板内容并添加到 Shadow DOM
        const templateContent = template.cloneNode(true);
        await shadow.appendChild(templateContent);
        const configScript = this.querySelector('script[type="application/json"]');
        this.configData = configScript ? JSON.parse(configScript.textContent) : {
            countries: [],
            states: [],
            cities: [],
        };
        this._countries = this.configData.countries;
        this._states = this.configData.states;
        this._cities = this.configData.cities;
        // 获取元素引用
        this.elements = {
            country: this.shadowRoot.getElementById('country'),
            state: this.shadowRoot.getElementById('state'),
            city: this.shadowRoot.getElementById('city'),
            street: this.shadowRoot.getElementById('street'),
            zip: this.shadowRoot.getElementById('zip')
        };
        // 设置事件监听
        this.elements.country.addEventListener('change', () => this._handleCountryChange());
        this.elements.state.addEventListener('change', () => this._handleStateChange());
        this.elements.city.addEventListener('change', () => this._updateCity());
        this.elements.street.addEventListener('input', () => this._updateStreet());
        this.elements.zip.addEventListener('input', () => this._updateZip());
    }
    getTemplate() {
        const template = fetch(this.templateUrl)
            .then(response => response.text())
            .then(data => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const template = doc.getElementById(this.templateId).content;
                return template;
            });
        return template;
    }
    async connectedCallback() {
        await this.init();
        await this._loadCountries();
        this._updateFromAttributes();
    }
    attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue === newValue) return;
        this[`_${name}`] = newValue;
        document.addEventListener('DOMContentLoaded', function () {
            // await this.elements;
            this._updateField(name);
        });
    }
    // 公共方法
    validate() {
        let isValid = true;
        // 添加具体的验证逻辑
        return isValid;
    }

    // 私有方法
    async _loadCountries() {
        this.elements.country.innerHTML = this._countries
            .map(c => `<option value="${c.code}">${c.name}</option>`)
            .join('');
    }

    async _loadStates(countryCode) {
        const states = this._states[countryCode] || [];
        this.elements.state.innerHTML = states
            .map(s => `<option value="${s}">${s}</option>`)
            .join('');
    }

    async _loadCities(state) {
        const cities = this._cities[state] || [];
        this.elements.city.innerHTML = cities
            .map(c => `<option value="${c}">${c}</option>`)
            .join('');
    }

    _updateFromAttributes() {
        this._countries.forEach(option => {
            if (option.code === this._country) {
                this.elements.country.value = this._country;
            }
        });

        this._loadStates(this._country).then(() => {
            this.elements.state.value = this._state;
            this._loadCities(this._state).then(() => {
                this.elements.city.value = this._city;
            });
        });

        this.elements.street.value = this._street;
        this.elements.zip.value = this._zip;
    }

    _updateField(field) {
        switch (field) {
            case 'country':
                this.elements.country.value = this._country;
                this._loadStates(this._country);
                break;
            case 'state':
                this.elements.state.value = this._state;
                this._loadCities(this._state);
                break;
            case 'city':
                this.elements.city.value = this._city;
                break;
            case 'street':
                this.elements.street.value = this._street;
                break;
            case 'zip':
                this.elements.zip.value = this._zip;
                break;
        }
    }

    _handleCountryChange() {
        this._country = this.elements.country.value;
        this.setAttribute('country', this._country);
        this._loadStates(this._country);
        const changeEvent = new Event('change', { bubbles: true, cancelable: true });
        this.elements.state.dispatchEvent(changeEvent);
    }

    _handleStateChange() {
        this._state = this.elements.state.value;
        this.setAttribute('state', this._state);
        this._loadCities(this._state);
        const changeEvent = new Event('change', { bubbles: true, cancelable: true });
        this.elements.city.dispatchEvent(changeEvent);
    }

    _updateCity() {
        this._city = this.elements.city.value;
        this.setAttribute('city', this._city);
    }

    _updateStreet() {
        this._street = this.elements.street.value;
        this.setAttribute('street', this._street);
    }

    _updateZip() {
        this._zip = this.elements.zip.value;
        this.setAttribute('zip', this._zip);
        this._validateZip();
    }

    _validateZip() {
        const patterns = {
            US: /^\d{5}(-\d{4})?$/,
            CA: /^[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d$/,
            CN: /^\d{6}$/
        };

        const pattern = patterns[this._country] || /.*/;
        const isValid = pattern.test(this._zip);

        const errorElement = this.shadowRoot.getElementById('zip-error');
        errorElement.style.display = isValid ? 'none' : 'block';
        errorElement.textContent = 'Invalid ZIP code format';
        return isValid;
    }
    // 属性getters
    get street() { return this._street; }
    get city() { return this._city; }
    get state() { return this._state; }
    get zip() { return this._zip; }
    get country() { return this._country; }

    // 属性setters
    set street(value) { this.setAttribute('street', value); }
    set city(value) { this.setAttribute('city', value); }
    set state(value) { this.setAttribute('state', value); }
    set zip(value) { this.setAttribute('zip', value); }
    set country(value) { this.setAttribute('country', value); }
}

customElements.define('wcs-selector-address', AddressSelector);